﻿#if UNITY_EDITOR
using System;
using UnityEditor;
using UnityEngine;

namespace AI.Graph.Editor {


    public abstract class CollapsibleNodeView<T> : NodeView<T> where T : CollapsibleNode {

        private float collapseHeight;
        private float collapsedAnimationValue;


        protected override void OnViewCreated () {
            base.OnViewCreated ();

            if (node.isCollapsed) {
                collapsedAnimationValue = 1;
            }
        }


        /// <summary>
        /// Draws all graph node controls.
        /// </summary>
        protected virtual void OnNodeGUI () {
            DrawDefaultNode ();
        }


        /// <summary>
        /// Draws a collapsible area.
        /// </summary>
        /// <param name="y">The start point.</param>
        /// <returns>Returns the size of the draw area.</returns>
        internal protected Rect DrawNodeCollapseArea (float y) {
            collapsedAnimationValue += node.isCollapsed ? Styles.collapseAnimationSpeed * canvas.deltaTime : -Styles.collapseAnimationSpeed * canvas.deltaTime;
            collapsedAnimationValue = Mathf.Clamp (collapsedAnimationValue, 0, 1);

            float extendedCenterHeight = (collapseHeight + (collapseHeight > 0 ? Styles.collapseAreaPaddingTop + Styles.collapseAreaPaddingBottom : 0)) * collapsedAnimationValue;

            Rect centerRect = new Rect (0, y, node.size.x, extendedCenterHeight);
            EditorGUI.DrawSolidTexture (centerRect, Styles.background100.color);

            try {
//            if (!Mathf.Approximately (collapsedAnimationValue, 0)) {
                GUILayout.BeginArea (new Rect (centerRect.x + Styles.collapseAreaPaddingLeft, centerRect.y + Styles.collapseAreaPaddingTop, centerRect.width - Styles.collapseAreaPaddingLeft - Styles.collapseAreaPaddingRight, extendedCenterHeight));

                Rect rect = EditorGUILayout.BeginVertical ();

//                GUI.enabled = canvas.IsNodeSelected (node);
                OnNodeGUI ();
//                GUI.enabled = true;


                EditorGUILayout.EndVertical ();

                if (Event.current.IsRepaintEvent ()) {
                    collapseHeight = rect.height;
                }

                GUILayout.EndArea ();

//            }
            }
            catch (ArgumentException e) {
                if (e.Message.StartsWith ("Getting control")) {
                    canvas.window.Repaint ();
                }
                else {
                    throw new ArgumentException (e.Message);
                }
            }

            EditorGUI.DrawSolidTexture (centerRect, Styles.outlineColor.color, new BorderWidth (Styles.outlineWidth, Styles.outlineWidth, 0, 0));

            return centerRect;
        }

    }


}
#endif